import { Component, ViewChild, ViewChildren, OnInit, DoCheck } from '@angular/core';

import { NavController, ModalController, AlertController, Platform, VirtualScroll, Scroll } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import {StatusBar} from "@ionic-native/status-bar";

import {DomSanitizer} from '@angular/platform-browser';

import { Common } from "../../../providers/common";
import { Config } from "../../../providers/config";

import _ from "lodash";
import { Content } from 'ionic-angular';
import {IpmCirculateModal} from "../circulate/circulate.modal";
import {CashService} from "./cash.service";
import {IpmCashDetailPage} from "./detail.component";

@Component({
	selector: 'page-ipm-cash',
	templateUrl: 'cash.html',
  providers: [CashService]
})
export class IpmCashPage implements OnInit,DoCheck {
	moa_page_name: any = "page-ipm-cash";
  moa_page_explain: any = "批量现金流试算";

  ngOnInit() {

  }

  ngDoCheck() {
    this.setDataGridHeight();
  }

  @ViewChild(Content) content: Content;

  items = [0];

  // 列表数据
  listData: any = [];

  // 页码
  pageIndex = 1;
  // 是否加载更多
  isLoadMore = true;

	hisDays = 20;
	baseValue = 1000;

	showQueryParams = false;
	showQueryCondition = true;

  maxDate = "";

  queryCondition = null;

  selectedFund = [];
  successFund = [];
  fundCode = "";

  @ViewChildren(VirtualScroll)
  virtualScrolls;

  @ViewChild(Scroll)
  rightScroll: Scroll;


  maxStartDate = "";
  minEndDate = "";

  selectedDate = [];
  backupSelectedDate = [];

  showLoading = false;

  userInfo = null;

  showByLandscape = false;

  rowHeight = 0;
  contentWidth = 0;
  fundLeftHeight = 0;
  fundRightHeight = 0;
  fundRightMarginTop = 0;

  rotateClass = "";

  funds_right_scroll_x = "";
  funds_left_scroll_x = "";
  fundsContentClass = "";
  scrollContentMarginTop = "";

  styleSheet; //样式表选项
  searchRequestTimes = 0;
  selectStyle;

	constructor(
		public navCtrl: NavController,
    public common: Common,
    public modalCtrl: ModalController,
    public alertCtrl: AlertController,
    public config: Config,
    public  plt: Platform,
    private sanitizer: DomSanitizer,
    public cashService: CashService,
	public storage: Storage,
	private statusBar: StatusBar
	) {

	  // console.log(this.formatNumberToAccountancy(_.toString(parseFloat("40.8").toFixed(2))));
    // this.maxDate = "2099-12-12";//this.common.getNowFormatDate();

    this.maxStartDate = this.common.getNowFormatDate();
    this.minEndDate =this.maxStartDate;

    this.initQueryCondition();

  }

  ionViewDidLoad() {

	  this.content.ionScroll.subscribe(($event: any) => {
	    this.setDataGridHeight();

    });

	  this.contentWidth = this.content.getContentDimensions().contentWidth;

    document.getElementById("fundLeft").onscroll = function () {
      document.getElementById("fundRight").scrollTop = document.getElementById("fundLeft").scrollTop;
    };

    document.getElementById("fundRight").onscroll = function () {
      document.getElementById("fundLeft").scrollTop = document.getElementById("fundRight").scrollTop;
    };

    console.log(window.orientation);
  }

  ionViewWillLeave() {
	  if (this.showByLandscape) {
      // this.statusBar.hide();
    }
  }

  /*ionViewDidEnter() {
	  let exitFullscreen = document.getElementById("exitFullscreen");
	  if (exitFullscreen) {
      exitFullscreen.style.display = "block";
    }
  }

  ionViewDidLeave() {
    let exitFullscreen = document.getElementById("exitFullscreen");
    if (exitFullscreen) {
      exitFullscreen.style.display = "none";
    }
  }*/

  initQueryCondition() {
    //初始化样式表选项下拉框
    this.cashService.getTableStyle().subscribe( res => {
      this.styleSheet = res;
      console.log(res);
    })

	  this.queryCondition = {
      fund_code: "",
      startDate: "",
      endDate: "",
      dataStyle: "10"
    };

	  this.queryCondition.startDate = this.common.getNowFormatDate();
	  this.queryCondition.endDate = this.common.getDate(6);

	  if (!this.config.isProduct) {
      this.queryCondition.startDate = "2017-07-31";
      this.queryCondition.endDate = "2017-08-01";
    }

    this.storage.get("userInfo").then(user => {
      this.userInfo = user;
      this.storage.get("selected_fund_cash" + this.userInfo.loginid).then(selected_fund => {
        if (selected_fund) {
          this.selectedFund = selected_fund;
          this.queryCondition.fund_code = _.map(this.selectedFund, "vc_fund_code");
        }
      });
    });
  }

  selectFund() {
    let profileModal = this.modalCtrl.create(IpmCirculateModal, {
      selectedFund: this.selectedFund
    });
    profileModal.onDidDismiss(data => {
      if (data && data != "close") {
        this.selectedFund = data;
        this.storage.set("selected_fund_cash" + this.userInfo.loginid, data);
        this.queryCondition.fund_code = _.map(this.selectedFund, "vc_fund_code");
      }
    });
    profileModal.present();
  }

	setShowQueryCondition() {
	  this.showQueryCondition = !this.showQueryCondition;
    // document.getElementById("gridRight").style.height = 60 * this.queryCondition.fund_code.length  + 34 + "px";
    this.setDataGridHeight();
	  this.content.scrollToTop();
  }

  setDataGridHeight() {
    let row = this.listData.length;
    let parentField = _.filter(this.listData, {expand: true});
    if (parentField && parentField.length > 0) {
      _.forEach(parentField, pf => {
        row += pf["datas"].length;
        let childField = _.filter(pf["datas"], {expand: true});
        if (childField && childField.length > 0) {
          _.forEach(childField, cf => {
            row += cf["child"].length;
          });
        }
      });
    }
    // console.log(row);
    if (document.getElementById("gridRight")) {
      document.getElementById("gridRight").style.height = 60 * (row + 1) + 60 + "px";
    }

  }

  setShowQueryParams() {
	  this.showQueryParams = !this.showQueryParams;
  }

  search() {
    this.isLoadMore = true;
	  if (this.queryCondition.fund_code === "") {
      let alert = this.alertCtrl.create({
        title: "提示",
        message: "请选择基金",
        buttons: [
          {
            text: "确定",
            role: 'cancel',
            handler: () => {
            }
          }
        ]
      });
      alert.present();
      return;
    }
    this.listData = [];
	  this.setShowQueryCondition();
	  this.showLoading = true;
    // document.getElementById("gridRight").style.height = 60 * this.queryCondition.fund_code.length  + 34 + "px";
    this.setDataGridHeight();
	  this.loadListData();
  }

  /**
   * [loadListData 加载列表数据]
   */
  loadListData() {
    let that = this;
    let funCode_Collection = _.chunk(this.queryCondition.fund_code, 20);
    this.searchRequestTimes = 0;

    _.forEach(funCode_Collection, (fundCode, fundIndex) => {
      this.cashService.getCashQueryBatchData(fundCode, that.queryCondition).subscribe( result => {
        this.searchRequestTimes++;
        if (this.searchRequestTimes == funCode_Collection.length) {
          this.showLoading = false;
        }
       
        if (result && result.length > 0) {
          this.selectStyle = result[0].dataStyle;
          console.log('selectStyle', this.selectStyle)
          this.successFund = [...this.successFund, ...fundCode];
          this.setDataGridHeight();
          _.forEach(result, returnDatas => {
            
            let fundData = {
              trialNo: returnDatas["trialNo"],
              fundNo: returnDatas["fundNo"],
              fundCode: returnDatas["fundCode"],
              fundName: returnDatas["fundName"],
              date: _.uniq(_.map(returnDatas.fieldDatas, "l_date")),
              totalData: [],
              expand: false,
              datas: []
            };
            
            let tempDate = [];
            tempDate = _.uniq(_.map(returnDatas.fieldDatas, "l_date"));
            this.selectedDate = [];
            this.backupSelectedDate = [];

            _.forEach(tempDate, date => {
              this.backupSelectedDate.push(date);
              date = date.substr(0, 4) + "-" + date.substr(4, 2) + "-" + date.substr(6, 2);
              let week = this.common.numToWeek(new Date(date).getDay(), 0);
              if (date === this.common.getNowFormatDate()) {
                date = date + "(" + week + ")";
                date = "<span style='color: red;'>" + date + "</span>";
              } else {
                date = date + "(" + week + ")";
              }
              date = this.sanitizer.bypassSecurityTrustHtml(date);
              this.selectedDate.push(date);
            });

            switch (returnDatas.dataStyle) {
              case "10":
                let fieldB0 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "b0"});
                console.log("fieldB0", fieldB0);
                let tempFieldB0 = _.map(fieldB0, "en_balance");
                console.log("tempFieldB0", tempFieldB0);
                _.forEach(tempFieldB0, b0 => {
                  let tempTotalData = {
                    data: "0",
                    color: "set-color"
                  };
                  tempTotalData.data = this.formatNumberToAccountancy(_.toString(parseFloat(_.toString(b0)).toFixed(2)));
                  fundData.totalData.push(tempTotalData);
                });
                console.log("fundData.totalData", fundData.totalData);
                break;
              case "20":
                let temp_fieldB0 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "b0"});
                let fieldA8 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a8"});
                let fieldA9 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a9"});
                let field90 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "90"});
                let fieldA0 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a0"});
                _.forEach(temp_fieldB0, (fb0, i) => {
                  let tempTotalData = {
                    data: "0",
                    color: "set-color"
                  };
                  if (fb0["en_balance"] < returnDatas["IPM_CASH_Threshold"]) {
                    //A8-A9*5%
                    let diff = 0;
                    if (!field90[i]["en_balance"] || parseFloat(field90[i]["en_balance"]) <= 0) {
                      diff = parseFloat(fieldA0[i]["en_balance"]) -
                        parseFloat(fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;
                    } else {
                      diff = parseFloat(fieldA8[i]["en_balance"]) -
                        parseFloat(fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;
                    }
  
                    tempTotalData.data = this.formatNumberToAccountancy(_.toString(parseFloat(fb0["en_balance"]).toFixed(2))) + "(" +
                      this.formatNumberToAccountancy(_.toString(diff.toFixed(2))) + ")";
                    if (parseFloat(fb0["en_balance"]) < returnDatas.IPM_CASH_Threshold) {
                      tempTotalData.color = "redColor";
                    }
                    // fundData.totalData.push(tempTotalData);
                  } else {
                    tempTotalData.data = this.formatNumberToAccountancy(_.toString(parseFloat(fb0["en_balance"]).toFixed(2)));
                    // fundData.totalData.push(tempTotalData);
                  }
                  fundData.totalData.push(tempTotalData);
                });
                break;
              case "21":
                let _temp_fieldB0 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "b0"});
                let _fieldA8 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a8"});
                let _fieldA9 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a9"});
                let _field90 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "90"});
                console.log("_field90>>>>", _field90);
                let _fieldA0 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a0"});
                _.forEach(_temp_fieldB0, (fb0, i) => {
                  let tempTotalData = {
                    data: "0",
                    color: "set-color"
                  };
                  if (fb0["en_balance"] < returnDatas["IPM_CASH_Threshold"]) {
                    //A8-A9*5%
  
                    let diff = 0;
                    if (!_field90[i]["en_balance"] || parseFloat(_field90[i]["en_balance"]) <= 0) {
                      diff = parseFloat(_fieldA0[i]["en_balance"]) -
                        parseFloat(_fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;
                    } else {
                      diff = parseFloat(_fieldA8[i]["en_balance"]) -
                        parseFloat(_fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;
                    }
  
                    /*let diff = parseFloat(_fieldA8[i]["en_balance"]) -
                      parseFloat(_fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;*/
                    tempTotalData.data = this.formatNumberToAccountancy(_.toString(parseFloat(fb0["en_balance"]).toFixed(2))) + "(" +
                      this.formatNumberToAccountancy(_.toString(diff.toFixed(2))) + ")";
                    if (parseFloat(fb0["en_balance"]) < returnDatas.IPM_CASH_Threshold) {
                      tempTotalData.color = "redColor";
                    }
                    // fundData.totalData.push(tempTotalData);
                  } else {
                    tempTotalData.data = this.formatNumberToAccountancy(_.toString(parseFloat(fb0["en_balance"]).toFixed(2)));
                    // fundData.totalData.push(tempTotalData);
                  }
                  fundData.totalData.push(tempTotalData);
                });
                break;
                case "22":
                  let rc_temp_fieldB0 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "b0"});
                  let rc_fieldA8 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a8"});
                  let rc_fieldA9 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a9"});
                  let rc_field90 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "90"});
                  console.log("rc_field90>>>>", rc_field90);
                  let rc_fieldA0 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a0"});
                  _.forEach(rc_temp_fieldB0, (fb0, i) => {
                    let tempTotalData = {
                      data: "0",
                      color: "set-color"
                    };
                    if (fb0["en_balance"] < returnDatas["IPM_CASH_Threshold"]) {
                      //A8-A9*5%
    
                      let diff = 0;
                      if (!rc_field90[i]["en_balance"] || parseFloat(_field90[i]["en_balance"]) <= 0) {
                        diff = parseFloat(rc_fieldA0[i]["en_balance"]) -
                          parseFloat(rc_fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;
                      } else {
                        diff = parseFloat(rc_fieldA8[i]["en_balance"]) -
                          parseFloat(rc_fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;
                      }
    
                      /*let diff = parseFloat(rc_fieldA8[i]["en_balance"]) -
                        parseFloat(_fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;*/
                      tempTotalData.data = this.formatNumberToAccountancy(_.toString(parseFloat(fb0["en_balance"]).toFixed(2))) + "(" +
                        this.formatNumberToAccountancy(_.toString(diff.toFixed(2))) + ")";
                      if (parseFloat(fb0["en_balance"]) < returnDatas.IPM_CASH_Threshold) {
                        tempTotalData.color = "redColor";
                      }
                      // fundData.totalData.push(tempTotalData);
                    } else {
                      tempTotalData.data = this.formatNumberToAccountancy(_.toString(parseFloat(fb0["en_balance"]).toFixed(2)));
                      // fundData.totalData.push(tempTotalData);
                    }
                    fundData.totalData.push(tempTotalData);
                  });
                break;
                case "23":
                  let rz_temp_fieldB0 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "b0"});
                  let rz_fieldA8 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a8"});
                  let rz_fieldA9 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a9"});
                  let rz_field90 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "90"});
                  console.log("rz_field90>>>>", rz_field90);
                  let rz_fieldA0 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a0"});
                  _.forEach(rz_temp_fieldB0, (fb0, i) => {
                    let tempTotalData = {
                      data: "0",
                      color: "set-color"
                    };
                    if (fb0["en_balance"] < returnDatas["IPM_CASH_Threshold"]) {
                      //A8-A9*5%
    
                      let diff = 0;
                      if (!rz_field90[i]["en_balance"] || parseFloat(_field90[i]["en_balance"]) <= 0) {
                        diff = parseFloat(rz_fieldA0[i]["en_balance"]) -
                          parseFloat(rz_fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;
                      } else {
                        diff = parseFloat(rz_fieldA8[i]["en_balance"]) -
                          parseFloat(rz_fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;
                      }
    
                      /*let diff = parseFloat(rz_fieldA8[i]["en_balance"]) -
                        parseFloat(_fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;*/
                      tempTotalData.data = this.formatNumberToAccountancy(_.toString(parseFloat(fb0["en_balance"]).toFixed(2))) + "(" +
                        this.formatNumberToAccountancy(_.toString(diff.toFixed(2))) + ")";
                      if (parseFloat(fb0["en_balance"]) < returnDatas.IPM_CASH_Threshold) {
                        tempTotalData.color = "redColor";
                      }
                      // fundData.totalData.push(tempTotalData);
                    } else {
                      tempTotalData.data = this.formatNumberToAccountancy(_.toString(parseFloat(fb0["en_balance"]).toFixed(2)));
                      // fundData.totalData.push(tempTotalData);
                    }
                    fundData.totalData.push(tempTotalData);
                  });
                break;
            }

            let cashType = _.uniq(_.map(returnDatas.fieldDatas, "vc_cash_type"));
            _.forEach(cashType, cash_type => {
              let temp = _.filter(returnDatas.fieldDatas, fd => {
                return fd["vc_cash_type"] == cash_type && fd["vc_top_type"] == "";
              });
  
              if (temp && temp.length > 0) {
                let cashEntity = {
                  fieldName: temp[0]["vc_type_name"],
                  fieldDatas: temp,
                  fieldNameColor: "set-color",
                  expand: false,
                  child: []
                };
  
                if (temp[0]["vc_cash_type"].indexOf("a") == 0 ||
                  temp[0]["vc_cash_type"].indexOf("b") == 0 ||
                  temp[0]["vc_cash_type"].indexOf("c") == 0) {
                  cashEntity["fieldNameColor"] += " font_weight_900";
                }
  
                _.forEach(temp, temp_data => {
                  if (temp_data["vc_cash_type"].indexOf("9") == 0 && parseFloat(temp_data["en_balance"]) < 0) {
                    temp_data["fieldColor"] = "redColor";
                  } else {
                    temp_data["fieldColor"] = "set-color";
                  }
  
                  if (temp_data["vc_cash_type"].indexOf("a") == 0 ||
                    temp_data["vc_cash_type"].indexOf("b") == 0 ||
                    temp_data["vc_cash_type"].indexOf("c") == 0) {
                    temp_data["fieldColor"] += " font_weight_900";
                  }
                });
  
                let temp_child = this.getChild(returnDatas, cash_type);
                let notNull = _.filter(temp, t => {
                  let compareResult = t["en_balance"] != "0" && t["en_balance"] != null && t["en_balance"] != "null";
                  // t["en_balance"] = this.formatNumberToAccountancy(_.toString(parseFloat(t["en_balance"]).toFixed(2)));
                  return compareResult;
                });
                if (notNull && notNull.length > 0) {
                  if (temp_child && temp_child.length > 0) {
                    _.forEach(temp_child, tc => {
                      let childNotNull = _.filter(tc.fieldDatas, tc2 => {
                        let compareResult = tc2["en_balance"] != "0" && tc2["en_balance"] != null && tc2["en_balance"] != "null";
                        // tc2["en_balance"] = this.formatNumberToAccountancy(_.toString(parseFloat(tc2["en_balance"]).toFixed(2)));
                        return compareResult;
                      });
  
                      if (childNotNull && childNotNull.length > 0) {
                        cashEntity.child.push(tc);
                      }
                    });
                  }
                  fundData.datas.push(cashEntity);
                } else {
                  if (temp_child && temp_child.length > 0) {
                    _.forEach(temp_child, tc => {
                      let childNotNull = _.filter(tc.fieldDatas, tc2 => {
                        let compareResult = tc2["en_balance"] != "0" && tc2["en_balance"] != null && tc2["en_balance"] != "null";
                        // tc2["en_balance"] = this.formatNumberToAccountancy(_.toString(parseFloat(tc2["en_balance"]).toFixed(2)));
                        return compareResult;
                      });
                      if (childNotNull && childNotNull.length > 0) {
                        cashEntity.child.push(tc);
                      }
                    });
                    if (cashEntity.child.length > 0) {
                      fundData.datas.push(cashEntity);
                    }
                  }
                }
              }
            });
            this.listData.push(fundData);
            
            if (document.getElementById("GridTitle")) {
              document.getElementById("GridTitle").style.width = 200 * this.selectedDate.length + "px";
            }
          })
          console.log('------listDatas------', this.listData)
        } else {
          this.setDataGridHeight();
        }
      })
     
    })

    // _.forEach(this.queryCondition.fund_code, (fundCode, fundIndex) => {
    //   this.cashService.getCashQueryData(fundCode, this.queryCondition).subscribe(returnDatas => {
    //     if (parseInt(fundIndex) == this.queryCondition.fund_code.length - 1) {
    //       this.showLoading = false;
    //     }

    //     console.log("#######", returnDatas);
    //     if (returnDatas) {

    //       this.successFund.push(fundCode);
    //       this.setDataGridHeight();

    //       let fundData = {
    //         trialNo: returnDatas["trialNo"],
    //         fundNo: returnDatas["fundNo"],
    //         fundCode: returnDatas["fundCode"],
    //         fundName: returnDatas["fundName"],
    //         date: _.uniq(_.map(returnDatas.fieldDatas, "l_date")),
    //         totalData: [],
    //         expand: false,
    //         datas: []
    //       };
    //       let tempDate = [];
    //       tempDate = _.uniq(_.map(returnDatas.fieldDatas, "l_date"));
    //       this.selectedDate = [];
    //       this.backupSelectedDate = [];
    //       _.forEach(tempDate, date => {
    //         this.backupSelectedDate.push(date);
    //         date = date.substr(0, 4) + "-" + date.substr(4, 2) + "-" + date.substr(6, 2);
    //         let week = this.common.numToWeek(new Date(date).getDay(), 0);
    //         if (date === this.common.getNowFormatDate()) {
    //           date = date + "(" + week + ")";
    //           date = "<span style='color: red;'>" + date + "</span>";
    //         } else {
    //           date = date + "(" + week + ")";
    //         }
    //         date = this.sanitizer.bypassSecurityTrustHtml(date);
    //         this.selectedDate.push(date);
    //       });

    //       switch (returnDatas.dataStyle) {
    //         case "10":
    //           let fieldB0 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "b0"});
    //           console.log("fieldB0", fieldB0);
    //           let tempFieldB0 = _.map(fieldB0, "en_balance");
    //           console.log("tempFieldB0", tempFieldB0);
    //           _.forEach(tempFieldB0, b0 => {
    //             let tempTotalData = {
    //               data: "0",
    //               color: "set-color"
    //             };
    //             tempTotalData.data = this.formatNumberToAccountancy(_.toString(parseFloat(_.toString(b0)).toFixed(2)));
    //             fundData.totalData.push(tempTotalData);
    //           });
    //           console.log("fundData.totalData", fundData.totalData);
    //           break;
    //         case "20":
    //           let temp_fieldB0 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "b0"});
    //           let fieldA8 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a8"});
    //           let fieldA9 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a9"});
    //           let field90 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "90"});
    //           let fieldA0 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a0"});
    //           _.forEach(temp_fieldB0, (fb0, i) => {
    //             let tempTotalData = {
    //               data: "0",
    //               color: "set-color"
    //             };
    //             if (fb0["en_balance"] < returnDatas["IPM_CASH_Threshold"]) {
    //               //A8-A9*5%
    //               let diff = 0;
    //               if (!field90[i]["en_balance"] || parseFloat(field90[i]["en_balance"]) <= 0) {
    //                 diff = parseFloat(fieldA0[i]["en_balance"]) -
    //                   parseFloat(fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;
    //               } else {
    //                 diff = parseFloat(fieldA8[i]["en_balance"]) -
    //                   parseFloat(fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;
    //               }

    //               tempTotalData.data = this.formatNumberToAccountancy(_.toString(parseFloat(fb0["en_balance"]).toFixed(2))) + "(" +
    //                 this.formatNumberToAccountancy(_.toString(diff.toFixed(2))) + ")";
    //               if (parseFloat(fb0["en_balance"]) < returnDatas.IPM_CASH_Threshold) {
    //                 tempTotalData.color = "redColor";
    //               }
    //               // fundData.totalData.push(tempTotalData);
    //             } else {
    //               tempTotalData.data = this.formatNumberToAccountancy(_.toString(parseFloat(fb0["en_balance"]).toFixed(2)));
    //               // fundData.totalData.push(tempTotalData);
    //             }
    //             fundData.totalData.push(tempTotalData);
    //           });
    //           break;
    //         case "21":
    //           let _temp_fieldB0 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "b0"});
    //           let _fieldA8 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a8"});
    //           let _fieldA9 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a9"});
    //           let _field90 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "90"});
    //           console.log("_field90>>>>", _field90);
    //           let _fieldA0 = _.filter(returnDatas.fieldDatas, {vc_cash_type: "a0"});
    //           _.forEach(_temp_fieldB0, (fb0, i) => {
    //             let tempTotalData = {
    //               data: "0",
    //               color: "set-color"
    //             };
    //             if (fb0["en_balance"] < returnDatas["IPM_CASH_Threshold"]) {
    //               //A8-A9*5%

    //               let diff = 0;
    //               if (!_field90[i]["en_balance"] || parseFloat(_field90[i]["en_balance"]) <= 0) {
    //                 diff = parseFloat(_fieldA0[i]["en_balance"]) -
    //                   parseFloat(_fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;
    //               } else {
    //                 diff = parseFloat(_fieldA8[i]["en_balance"]) -
    //                   parseFloat(_fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;
    //               }

    //               /*let diff = parseFloat(_fieldA8[i]["en_balance"]) -
    //                 parseFloat(_fieldA9[i]["en_balance"]) * returnDatas["IPM_CASH_Threshold"] / 100;*/
    //               tempTotalData.data = this.formatNumberToAccountancy(_.toString(parseFloat(fb0["en_balance"]).toFixed(2))) + "(" +
    //                 this.formatNumberToAccountancy(_.toString(diff.toFixed(2))) + ")";
    //               if (parseFloat(fb0["en_balance"]) < returnDatas.IPM_CASH_Threshold) {
    //                 tempTotalData.color = "redColor";
    //               }
    //               // fundData.totalData.push(tempTotalData);
    //             } else {
    //               tempTotalData.data = this.formatNumberToAccountancy(_.toString(parseFloat(fb0["en_balance"]).toFixed(2)));
    //               // fundData.totalData.push(tempTotalData);
    //             }
    //             fundData.totalData.push(tempTotalData);
    //           });
    //           break;
    //       }

    //       let cashType = _.uniq(_.map(returnDatas.fieldDatas, "vc_cash_type"));
    //       _.forEach(cashType, cash_type => {
    //         let temp = _.filter(returnDatas.fieldDatas, fd => {
    //           return fd["vc_cash_type"] == cash_type && fd["vc_top_type"] == "";
    //         });

    //         if (temp && temp.length > 0) {
    //           let cashEntity = {
    //             fieldName: temp[0]["vc_type_name"],
    //             fieldDatas: temp,
    //             fieldNameColor: "set-color",
    //             expand: false,
    //             child: []
    //           };

    //           if (temp[0]["vc_cash_type"].indexOf("a") == 0 ||
    //             temp[0]["vc_cash_type"].indexOf("b") == 0 ||
    //             temp[0]["vc_cash_type"].indexOf("c") == 0) {
    //             cashEntity["fieldNameColor"] += " font_weight_900";
    //           }

    //           _.forEach(temp, temp_data => {
    //             if (temp_data["vc_cash_type"].indexOf("9") == 0 && parseFloat(temp_data["en_balance"]) < 0) {
    //               temp_data["fieldColor"] = "redColor";
    //             } else {
    //               temp_data["fieldColor"] = "set-color";
    //             }

    //             if (temp_data["vc_cash_type"].indexOf("a") == 0 ||
    //               temp_data["vc_cash_type"].indexOf("b") == 0 ||
    //               temp_data["vc_cash_type"].indexOf("c") == 0) {
    //               temp_data["fieldColor"] += " font_weight_900";
    //             }
    //           });

    //           let temp_child = this.getChild(returnDatas, cash_type);
    //           let notNull = _.filter(temp, t => {
    //             let compareResult = t["en_balance"] != "0" && t["en_balance"] != null && t["en_balance"] != "null";
    //             // t["en_balance"] = this.formatNumberToAccountancy(_.toString(parseFloat(t["en_balance"]).toFixed(2)));
    //             return compareResult;
    //           });
    //           if (notNull && notNull.length > 0) {
    //             if (temp_child && temp_child.length > 0) {
    //               _.forEach(temp_child, tc => {
    //                 let childNotNull = _.filter(tc.fieldDatas, tc2 => {
    //                   let compareResult = tc2["en_balance"] != "0" && tc2["en_balance"] != null && tc2["en_balance"] != "null";
    //                   // tc2["en_balance"] = this.formatNumberToAccountancy(_.toString(parseFloat(tc2["en_balance"]).toFixed(2)));
    //                   return compareResult;
    //                 });

    //                 if (childNotNull && childNotNull.length > 0) {
    //                   cashEntity.child.push(tc);
    //                 }
    //               });
    //             }
    //             fundData.datas.push(cashEntity);
    //           } else {
    //             if (temp_child && temp_child.length > 0) {
    //               _.forEach(temp_child, tc => {
    //                 let childNotNull = _.filter(tc.fieldDatas, tc2 => {
    //                   let compareResult = tc2["en_balance"] != "0" && tc2["en_balance"] != null && tc2["en_balance"] != "null";
    //                   // tc2["en_balance"] = this.formatNumberToAccountancy(_.toString(parseFloat(tc2["en_balance"]).toFixed(2)));
    //                   return compareResult;
    //                 });
    //                 if (childNotNull && childNotNull.length > 0) {
    //                   cashEntity.child.push(tc);
    //                 }
    //               });
    //               if (cashEntity.child.length > 0) {
    //                 fundData.datas.push(cashEntity);
    //               }
    //             }
    //           }
    //         }
    //       });
    //       this.listData.push(fundData);
    //       if (document.getElementById("GridTitle")) {
    //         document.getElementById("GridTitle").style.width = 200 * this.selectedDate.length + "px";
    //       }
    //       console.log(this.listData);
    //     } else {
    //       this.setDataGridHeight();
    //     }
    //   });
    // });
  }

  expandField(item, type, parent) {
    switch (type) {
      case '1':
        item.expand = !item.expand;
        this.setDataGridHeight();
        break;
      case '2':
        if (item.child && item.child.length > 0) {
          item.expand = !item.expand;
        }
        this.setDataGridHeight();
        break;
    }
  }

  /**
   * 获取子字段
   * @param returnDatas
   * @param cash_type
   * @returns {Array}
   */
  getChild(returnDatas, cash_type) {
    let result = [];
    let child = _.filter(returnDatas.fieldDatas, rdf => {
      return rdf["vc_top_type"] == cash_type;
    });

    if (child && child.length > 0) {
      let childCashType = _.uniq(_.map(child, "vc_cash_type"));
      _.forEach(childCashType, child_cash_type => {
        let temp = _.filter(child, c => {
          return c["vc_cash_type"] === child_cash_type;
        });
        if (temp && temp.length > 0) {
          _.forEach(temp, temp_data => {
            if (temp_data["vc_cash_type"].indexOf("9") == 0 && parseFloat(temp_data["en_balance"]) < 0) {
              temp_data["fieldColor"] = "redColor";
            } else {
              temp_data["fieldColor"] = "grayColor";
            }
          });
          let cashEntity = {
            fieldName: temp[0]["vc_type_name"],
            fieldColor: "set-color",
            fieldDatas: temp
          };
          result.push(cashEntity);
        }
      });
    }
    return result;
  }

  /**
   * [doInfinite 加载更多]
   * @param {[type]} infiniteScroll [事件]
   */
  doInfinite(infiniteScroll) {
    if (this.pageIndex != 1) {
      console.info("-----------infiniteScroll------------");
      console.info(infiniteScroll);
      if (this.isLoadMore) {
        // this.loadListData(this.pageIndex, infiniteScroll, null);
      } else {
        infiniteScroll.complete();
      }
    } else {
      infiniteScroll.complete();
    }
  }
  /**
   * [doRefresh 下拉刷新]
   * @param {[type]} refresher [事件]
   */
  doRefresh(refresher) {
    this.pageIndex = 1;
    this.isLoadMore = true;
    // this.loadListData(this.pageIndex, null, refresher);
  }

  goPos() {
    let offsetHeight = document.getElementById("inputEnValue").offsetHeight;
    if (this.plt.is("android")) {
      console.log(offsetHeight);
      this.content.scrollTo(0, offsetHeight * 5);
    }
  }

  formatNumberToAccountancy(target) {
    let result = "";
    if (target) {
      let fix = "";
      if (target.indexOf("-") > -1) {
        fix = "-";
        target = _.replace(target, "-", "");
      }
      let temp = target.split(".");
      if (temp[0]) {
        let length = temp[0].length;
        let remainder = length % 3;
        let mark = remainder == 0 ? remainder : remainder - 1;
        for (var i = length - 3; i > mark; i -=3 ) {
          result = "," + temp[0].substr(i, 3) + result;
        }
        result = fix + temp[0].substr(0, remainder == 0 ? 3 : remainder) + result;
        if (temp[1]) {
          result = result + "." + temp[1].substr(0, 2);
          if (temp[1].length == 1) {
            result = result + "." + temp[1] + "0";
          }
        } else {
          result = result + ".00";
        }
      }
    }
    return result;
  }

  /**
   * 切换横竖屏
   */
  setShowByLandscape(type) {
    if (!this.showByLandscape && type === 2) {
      return false
    }
    this.showByLandscape = !this.showByLandscape;
    if (this.showByLandscape) {
	    this.statusBar.hide();
      /*this.plt.ready().then(() => {
        if (this.showByLandscape == true) {
          this.statusBar.hide();
        }
      });*/

      let child = document.getElementById("circulateContent").getElementsByClassName("scroll-content")[0];
      child["style"]["-webkit-transform"] = "rotate(90deg)";
      child["style"]["-webkit-transform-origin"] = "top";
      child["style"].height = this.contentWidth + "px";
      child["style"].width = document.getElementById("circulateContent").offsetHeight + "px";
      child["style"].zIndex = "99999";
      this.scrollContentMarginTop = child["style"].marginTop;
      child["style"].marginTop = document.getElementById("circulateContent").offsetHeight / 2 + "px";
      child["style"].marginLeft = (this.contentWidth - document.getElementById("circulateContent").offsetHeight / 2) + "px";

      document.getElementById("fundLeft").style.height = this.contentWidth + "px";
      document.getElementById("fundRight").style.height = this.contentWidth + "px";
      document.getElementById("fundRight").style.marginTop = 0 - this.contentWidth + "px";
      document.getElementById("fundLeft").style.maxWidth = "25%";
      document.getElementById("fundRight").style.maxWidth = "75%";
      document.getElementById("fundRight").style.width = "75%";
      document.getElementById("fundRight").style.marginLeft = "25%";

      let circulateContent = document.getElementById("circulateContent").offsetHeight;
      document.getElementById("dataRow").style.width = circulateContent - 10 + "px";

      /*this.rotateClass = "rotate_90";
      this.rowHeight = document.getElementById("dataRow").offsetHeight;
      this.fundLeftHeight = document.getElementById("fundLeft").offsetHeight;
      this.fundRightHeight = document.getElementById("fundRight").offsetHeight;



      let cashHeader = document.getElementById("cashHeader").offsetHeight;
      let headerDivider = document.getElementById("headerDivider").offsetHeight;

      // document.getElementById("fundsDetailMsg").style.marginTop = headerDivider + "px";

      this.funds_left_scroll_x = "funds-left-scroll-x";
      this.funds_right_scroll_x = "funds-right-scroll-x";
      this.fundsContentClass = "fundsContent";

      let child = document.getElementById("circulateContent").getElementsByClassName("scroll-content")[0];
      this.scrollContentMarginTop = child["style"].marginTop;

      child["style"].marginTop = "0px";
      child["style"].marginBottom = "0px";*/
    } else {
	    this.statusBar.show();
      this.plt.ready().then(() => {
        if (this.showByLandscape == false) {
          this.statusBar.show();
        }
      });

      let child = document.getElementById("circulateContent").getElementsByClassName("scroll-content")[0];
      child["style"]["-webkit-transform"] = "rotate(0deg)";
      child["style"].marginTop = this.scrollContentMarginTop;
      child["style"].marginBottom = "0px";
      child["style"].height = "auto";
      child["style"].width = "auto";
      child["style"].marginLeft = "0px";

      document.getElementById("dataRow").style.width = this.contentWidth + "px";
      document.getElementById("fundLeft").style.height = this.fundLeftHeight + "px";
      document.getElementById("fundRight").style.height = this.fundRightHeight + "px";
      document.getElementById("fundRight").style.marginTop = "0";
      document.getElementById("fundLeft").style.maxWidth = "42%";
      document.getElementById("fundRight").style.maxWidth = "58%";
      document.getElementById("fundRight").style.marginLeft = "42%";


      /*this.rotateClass = "";


      this.funds_left_scroll_x = "";
      this.funds_right_scroll_x = "";
      this.fundsContentClass = "";

      */

    }
  }

  scrollHandler(e) {

  }

  viewCashDetail(field, item, index) {
  
    let trial_no = field.trialNo;
    if(["22", "23"].indexOf(this.selectStyle) > -1) {
      trial_no = trial_no.split(',')[index].replace(/\'/g, '');
    }

    let disabledCashType = ["a", "b", "c"];
    if (disabledCashType.indexOf(item["vc_cash_type"].substr(0, 1)) > -1) {
      // this.common.alertMessage("该资金类型无现金流明细");
    } else {
      let params = {
        trialNo: trial_no,
        fundNo: field.fundNo,
        l_date: this.backupSelectedDate[index],
        cashType: item["vc_cash_type"]
      };
      console.log(params);
      let isRedemption = false;
      if (item["vc_type_name"] === "TA申赎资金") {
        isRedemption = true;
      }

      this.plt.ready().then(() => {
        if (this.showByLandscape == true) {
          this.statusBar.hide();
        }
      });

      this.navCtrl.push(IpmCashDetailPage, {
        params: params,
        isRedemption: isRedemption,
        showByLandscape: this.showByLandscape
      }).then(() => {
        if (this.showByLandscape) {
          // this.statusBar.hide();
        }
      });
    }

  }

}

